/* Author: Olivo Pablo
 */


$(document).ready(function() {


    bodyelem = $("html")
//    
//    
//    if($.browser.msie && $.browser.version=="6.0"){
//     
//        $(document).pngFix();
//    };


    /**
     * place selected class to nav
     */
    var path = location.pathname.substring(1);
    //if page defined/override from php view
    if (typeof set_page !== 'undefined') {
        $('nav a[href$="' + set_page + '"]').addClass('selected');
    }

    else if (path) {
        $('nav a[href$="' + path + '"]').addClass('selected');

    }
    else {
        $('nav a:first-child').eq(0).addClass('selected');
    }


    //link on partner pages
    if ($.fn.linkify) {
        $('.linkify').linkify(function(links) {
            links.attr('target', '_blank')
        });
    }

    //    if($.browser.msie && $.browser.version<="8.0"){
    //     
    //    
    //    };
    //    


    /***************TENTANG KAMI PAGE***************/
    var submenu = $('#submenu')
    if (submenu.length > 0) {

        submenuContent = $('.submenu-content');

        //if hash defined/override from php view
        if (typeof set_hash !== 'undefined') {
            init_section = set_hash;
            console.log(init_section);
        }
        else if (location.hash) {
            init_section = location.hash;//get hash if any  
        }
        else {
            init_section = 'section.init';
        }

        //check if url has hash
        submenuselected = submenu.find('a[href$="' + init_section + '"]');
        if (submenuselected.length > 0)
        {
            submenuselected.parent().addClass('selected');//select menu base on hash
        } else {
            submenu.find('li:first-child').addClass('selected');//select first menu
        }



        submenuContent.children().not(init_section + ',section.tagline,.clear').hide(500);

        //on submenu click
        $('.scroll-nav').click(function(e) {
            e.preventDefault();
            $target = $(this).attr('href');

            //if target is hidden
            if ($($target).is(':hidden')) {
                //showing target
                submenuContent.children().not('section.tagline,.clear').fadeOut(500);
                submenuContent.find($target).fadeIn(800);
            }
            $(this).parent().siblings().removeClass('selected');
            $(this).parent().addClass('selected');
        });


        //fixed submenu
        var main_width = $('#main').width();  //get #main width
        // grab the initial top offset of the navigation
        var sticky_navigation_offset_top = $('#submenu').offset().top;
        // our function that decides weather the navigation bar should have "fixed" css position or not.
        var sticky_navigation = function() {


            var scroll_top = bodyelem.scrollTop(); // our current vertical position from the top          
            //  
            // if we've scrolled more than the navigation, change its position to fixed to stick to top,
            // otherwise change it back to relative
            if (screen.width > 480) {
                if (scroll_top > sticky_navigation_offset_top) {//if current view > /higher than menu
                    $('#submenu').css({
                        position: 'fixed',
                        top: 0,
                        width: main_width
                    });

                } else {
                    $('#submenu').css({
                        'position': 'relative'
                    });
                }
            }
        }




        // run our function on load
        sticky_navigation();
        // and run it again every time you scroll


        if (window.Touch)
        {

            document.ontouchmove = function() {
                sticky_navigation();
            }
        }
        else
        {
            $(window).scroll(function() {
                sticky_navigation();
            });
        }







        /*****iframe loading*/
        $('#submenu').find('.iframe-container').click(function() {
            if ($('div.iframe').eq(0).html("")) {
                bodyelem.find('div.iframe').eq(0).html('<iframe src="https://docs.google.com/file/d/0B1kn6KuaOLx-elZjakhBNkhoZUk/preview" class="full" height="480px"></iframe>');
                bodyelem.find('div.iframe').eq(1).html('<iframe src="https://docs.google.com/file/d/0B1kn6KuaOLx-aTY1UEdaZFV4VEU/preview" class="full" height="480px"></iframe>');
            }
        }
        )



    }

    /**KARYA-EXPERIMENTAL*/

    if ($('.karya-list-experimental').length > 0) {
        var karyalist = $('.karya-list');
        karyalistimg = karyalist.find('img');//change to pointer
        karyalistimg.css('cursor', 'pointer');//change to pointer

        karyalistimg.hover(function() {
            $(this).css({
                opacity: '0.3'
            });
            $(this).after('<div class="zoom">zoom</div>');
        }, function() {
            $(this).css({
                opacity: '1'
            });
            $('.zoom').remove();
        })


        karyalistimg.click(function() {
            karyabig = $('.karya-big');
            if (karyabig.is(':hidden')) {
                karyabig.transit({
                    display: 'block'

                }, 'slow')
                karyabig.transit({
                    height: '400px'

                }, 'slow')

            }
            karyabig.empty();
            imglink = this.src;
            karyabig.append('<img src="' + imglink + '">');
        });

    }
    /**KARYA*/
    var karyawrapper = $('.karya-wrapper');
    if (karyawrapper.length > 0) {

        $("a.cbox_group").colorbox({
            rel: 'cbox_group',
            opacity: '0',
            current: "",
            previous: "<",
            next: ">",
            close: "X"
        });
    }
    if ($('a.cbox_img').length) {
        $('a.cbox_img').colorbox()
    }

    $(window).resize(function() {

    });

    /******************************/

    $('#right article section').animate({
        opacity: '1'
    }, 'slow')

    if ($.scrolldeck) {
        var deck = new $.scrolldeck({
            buttons: '.scroll-nav',
            duration: 600,
            easing: 'easeInOutExpo',
            offset: 0
        });

    }




    if ($('#contact-us').length > 0) {
        $('input[type=text]').click(function() {
            $(this).removeClass('error').val('');
        })
        contactid = $('#contact-us');
        contactid.validate({
            onsubmit: true,
            onkeyup: false,
            submitHandler: function() {
                var data = $('#contact-us').serialize();
                url = contactid.attr('action');
                $.ajax({
                    type: 'POST',
                    url: url,
                    data: data,
                    success: function() {
                        $("#form-result").html('Pesan telah dikirim. Terima kasih.');
                        contactid.find('input[type=text],textarea').val('');
                    },
                    dataType: 'text'
                }).fail(function() {
                    $("#form-result").html('Pesan gagal dikirim. Coba ulangi lagi.')
                });

            },
            errorPlacement: function(error, element) {
                element.addClass('error').val('harus diisi');
            },
            debug: true
        });
    }

    if ($('#wysiwyg').length > 0) {
        new nicEditor({
            iconsPath: 'http://cfs-truss.com/public/js/libs/nicedit/icons.gif',
            fullPanel: true
        }).panelInstance('wysiwyg');
    }

    if ($('#wysiwyg-simple').length > 0) {
        new nicEditor({
            iconsPath: 'http://cfs-truss.com/public/js/libs/nicedit/icons.gif',
            buttonList: ['bold', 'italic', 'underline', 'left', 'center', 'right', 'justify', 'ol', 'ul', 'link', 'unlink', 'xhtml']
        }).panelInstance('wysiwyg-simple');
    }

    if ($('div.list').find('.row').length > 0) {
        listrow = $('div.list').find('.row');
        listrow.not('.header').css('cursor', 'pointer');

        listrow.find('.column').not('.panel,.normal').toggle(function() {
            $(this).siblings('.content').transit({
                display: 'block'
            }, 500);
        }, function() {
            $(this).siblings('.content').transit({
                display: 'none'
            }, 500);
        })
    }

    function centercontainer(parent, target) {
        pwidth = parent.width(), twidth = target.width();
        whitespace = pwidth - twidth;
        margin = whitespace / 2;
        target.css({
            left: margin
        });
        console.log(margin);
    }



    carouselcontainer = $('#revolver_carousel');
    //check if plugin loaded    
    if (carouselcontainer.length > 0) {

        var my_carousel = new Revolver(carouselcontainer, {
            autoPlay: false,
            slideClass: 'carousel'
        });

        caronextslide = $('.carousel-nav-wrapper').find('.next');
        caroprevslide = $('.carousel-nav-wrapper').find('.prev');

        // bind click events to all .goto elements in #bullets
        caronextslide.click(function(e) {
            e.preventDefault();
            my_carousel.next();

        });
        caroprevslide.click(function(e) {
            e.preventDefault();
            my_carousel.previous();
        });
    }

    var backtoptarget = $('.back-top');
    var to_top_navigation = function() {

        var scroll_top = bodyelem.scrollTop(); // our current vertical position from the top            
        // if we've scrolled more than the navigation, change its position to fixed to stick to top,
        // otherwise change it back to relative
        if (screen.width > 480) {
            if (scroll_top > 500) {//if current view > /higher than menu
                backtoptarget.css({
                    display: 'block'
                });

            } else {
                backtoptarget.css({
                    display: 'none'
                });
            }
        }
    }

    backtoptarget.click(function() {
        $(bodyelem).animate({
            scrollTop: 0
        }, 'slow')
    });

    $(window).scroll(function() {
        to_top_navigation();
    });

    //hover karya thumb
    $('.karya-list,.back-top,.nav-wrapper li img').hover(function() {

        $(this).transit({
            opacity: '0.6'
        })

    },
            function() {

                $(this).transit({
                    opacity: '1'
                })

            })

    $("div.heading-home").find('li').each(function() {
        var text = $(this).html();
        var first = $('<span>' + text.charAt(0) + '</span>').addClass('dropcap');
        $(this).html(text.substring(1)).prepend(first);
    });

    $('.medials').find('a.icon').hover(function() {
        //reset all


        //get initial and calculate newY position
        initial = $(this).css('background-position');
        arrayi = initial.split(" ");
        y = parseInt(arrayi[1]);
        newY = y + 32;

        $(this).css({
            'background-position': '0 ' + newY + 'px'
        })

    }
    ,
            function() {
                $('.medial').find('a.icon').removeAttr('style');

            })

    if ($('.open-dialog')) {
        $('.open-dialog,.close-dialog').on('click', function() {
            target = $(this).parent().find('.dialog-box');
            if (target.is(':visible')) {
                target.hide('fast');
            }
            else {
                target.show('slow');
            }
        })
    }

    slide_container = $('.flexslider');
    //check if plugin loaded    
    if (slide_container.length > 0) {
        slide_caption = slide_container.find('.slide_caption');
        //initalizing flexslider
        $('.flexslider').flexslider({
            //{NEW} String: Prefix string attached to the class of every element generated by the plugin
            selector: ".slides > .slide", //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
            animation: "slide", //String: Select your animation type, "fade" or "slide"
            easing: "swing", //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
            direction: "horizontal", //String: Select the sliding direction, "horizontal" or "vertical"
            //Integer: The slide that the slider should start on. Array notation (0 = first slide)
            slideshow: true, //Boolean: Animate slider automatically
            slideshowSpeed: 4000, //Integer: Set the speed of the slideshow cycling, in milliseconds
            animationSpeed: 800, //Integer: Set the speed of animations, in milliseconds
            //Boolean: Randomize slide order
            directionNav: false, //Boolean: Create navigation for previous/next navigation? (true/false)
            // Usability features
            pauseOnAction: true, //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
            pauseOnHover: false, //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
            useCSS: true, //{NEW} Boolean: Slider will use CSS3 transitions if available
            touch: true, //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
            video: false,
            _animateActiveCaption: function() {
                slide_container.find('.flex-active-slide').find('.slide_caption').animate({
                    opacity: 1,
                    paddingLeft: '15px'
                }, 800)
            }
            ,
            before: function() {
                slide_caption.css({
                    opacity: 0,
                    paddingLeft: '0'
                })
            },
            after: function() {
                slide_caption.css({
                    opacity: 0,
                    paddingLeft: '0'
                })
                this._animateActiveCaption()

            },
            start: function() {
                this._animateActiveCaption()
            }

        });





        nextslide = slide_container.find('.nav-wrapper').find('.next');
        prevslide = slide_container.find('.nav-wrapper').find('.prev');

        // bind click events to all .goto elements in #bullets
        nextslide.click(function(e) {
            $('.flexslider').flexslider('next');
        });
        prevslide.click(function(e) {
            $('.flexslider').flexslider('prev');
        });
    }
    if ($('a.back').length > 0) {

        $('a.back').on('click', function() {
            parent.history.back();
            return false;
        }).css({
            cursor: 'pointer'
        });
    }


})//end of jquery



$(window).load(function() {
    // Animate loader off screen
    $('#overlay').fadeOut(1000);


    if ($(".dropdown").is(':visible')) {
        trigger = $(".dropdown");
        target = $('nav').find('li').not('li.dropdown');
        $("li.dropdown").toggle(function() {
            trigger.find('a').text('Hide')
            target.show(400);
        },
                function() {
                    trigger.find('a').text('Menu')
                    target.hide(400);
                });
        target.hide();
    }

});
